import { type Layout, Responsive, WidthProvider } from 'react-grid-layout';
import AddedItem from '@/components/Template/AddedItem';
import type { DragItemType, TemplateType } from '@/types/template';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';

// 包装响应式组件
const ResponsiveGridLayout = WidthProvider(Responsive);

interface DraggableGridProps {
  type: TemplateType;
  addedItems: DragItemType[];
  onLayoutChange?: (currentLayout: Layout[]) => void;
  onItemClick?: (item: DragItemType) => void;
  onItemDelete?: (item: DragItemType) => void;
  onValueChange?: (item: DragItemType, value: string, reason?: string) => void;
}
const DraggableGrid = ({
  type,
  addedItems,
  onLayoutChange,
  onItemClick,
  onItemDelete,
  onValueChange,
}: DraggableGridProps) => {
  // 初始化布局状态
  const layout = addedItems.map((item) => ({
    i: item.id.toString(),
    x: item.x,
    y: item.y,
    w: item.w,
    h: item.h,
  }));
  const layouts = {
    lg: layout,
    md: layout,
    sm: layout,
  };

  // 处理布局变化（拖拽后会触发）
  const handleLayoutChange = (currentLayout: Layout[]) => {
    // 更新布局状态
    onLayoutChange?.(currentLayout);
  };

  return (
    <ResponsiveGridLayout
      draggableHandle=".drag-handle"
      layouts={layouts}
      breakpoints={{ lg: 1200, md: 996, sm: 768 }}
      cols={{ lg: 24, md: 24, sm: 24 }}
      rowHeight={10}
      margin={[40, 10]}
      // 启用拖拽功能（默认就是true，但显式设置更清晰）
      isDraggable={type === 'edit'}
      // 可以禁用调整大小（只保留拖拽功能）
      isResizable={type === 'edit'}
      // 拖拽时的回调
      // 拖拽结束的回调
      // 布局变化的回调
      onLayoutChange={handleLayoutChange}
    >
      {addedItems.map((item) => (
        <div key={item.id}>
          <AddedItem
            type={type}
            item={item}
            onClick={onItemClick}
            onDelete={onItemDelete}
            onValueChange={onValueChange}
          />
        </div>
      ))}
    </ResponsiveGridLayout>
  );
};

export default DraggableGrid;
